#include "FoodManager.h"
#include <algorithm>
#include <cmath>

extern Container *Game_Page;

FoodManager::FoodManager(Container *parent, int maxCount, int size)
    : parentContainer(parent), maxFoodCount(maxCount), foodSize(size), gen(rd()),
      disType(0, 99)
{
}

FoodManager::~FoodManager()
{
}

bool FoodManager::isValidPosition(int x, int y, const Snake &snake)
{
    if (!parentContainer)
        return false;

    // 检查边界
    if (x < 0 || y < 0 ||
        x + foodSize > parentContainer->get_width() ||
        y + foodSize > parentContainer->get_height())
    {
        return false;
    }

    // 检查是否在禁止刷新区域 (0,0 到 80,100)
    if (x >= FORBIDDEN_X_MIN && x <= FORBIDDEN_X_MAX &&
        y >= FORBIDDEN_Y_MIN && y <= FORBIDDEN_Y_MAX)
    {
        return false;
    }

    // 检查是否与现有食物重叠
    for (const auto &food : foods)
    {
        if (!food)
            continue;

        int fx = food->getX();
        int fy = food->getY();

        // 使用更精确的重叠检测
        bool xOverlap = (x < fx + foodSize) && (x + foodSize > fx);
        bool yOverlap = (y < fy + foodSize) && (y + foodSize > fy);

        if (xOverlap && yOverlap)
        {
            return false;
        }
    }

    return true;
}

bool FoodManager::isPositionSafe(int x, int y, const Snake &snake, int safeDistance)
{
    // 检查是否在禁止区域
    if (x >= FORBIDDEN_X_MIN && x <= FORBIDDEN_X_MAX &&
        y >= FORBIDDEN_Y_MIN && y <= FORBIDDEN_Y_MAX)
    {
        return false;
    }

    // 原有的安全距离检查
    // 这里需要根据Snake类的具体实现来完善
    // 暂时返回true，您可以根据需要实现具体的蛇身避让逻辑
    return true;
}

void FoodManager::getRandomPosition(int &x, int &y)
{
    if (!parentContainer)
        return;

    // 生成位置时避开禁止区域
    int maxAttempts = 50;
    int attempts = 0;

    do
    {
        // 如果父容器宽度足够，可以从禁止区域右侧开始生成
        if (parentContainer->get_width() > FORBIDDEN_X_MAX + foodSize)
        {
            std::uniform_int_distribution<> disX(FORBIDDEN_X_MAX + foodSize,
                                                 parentContainer->get_width() - foodSize);
            x = disX(gen);
        }
        else
        {
            std::uniform_int_distribution<> disX(0, parentContainer->get_width() - foodSize);
            x = disX(gen);
        }

        // 如果父容器高度足够，可以从禁止区域下方开始生成
        if (parentContainer->get_height() > FORBIDDEN_Y_MAX + foodSize)
        {
            std::uniform_int_distribution<> disY(FORBIDDEN_Y_MAX + foodSize,
                                                 parentContainer->get_height() - foodSize);
            y = disY(gen);
        }
        else
        {
            std::uniform_int_distribution<> disY(0, parentContainer->get_height() - foodSize);
            y = disY(gen);
        }

        // 确保位置对齐到网格（可选）
        x = (x / 10) * 10;
        y = (y / 10) * 10;

        attempts++;

    } while (attempts < maxAttempts &&
             (x >= FORBIDDEN_X_MIN && x <= FORBIDDEN_X_MAX &&
              y >= FORBIDDEN_Y_MIN && y <= FORBIDDEN_Y_MAX));

    // 如果多次尝试后仍在禁止区域，强制设置到安全位置
    if (x >= FORBIDDEN_X_MIN && x <= FORBIDDEN_X_MAX &&
        y >= FORBIDDEN_Y_MIN && y <= FORBIDDEN_Y_MAX)
    {
        x = FORBIDDEN_X_MAX + foodSize + 10;
        y = FORBIDDEN_Y_MAX + foodSize + 10;

        // 确保不超出边界
        if (x + foodSize > parentContainer->get_width())
            x = parentContainer->get_width() - foodSize - 10;
        if (y + foodSize > parentContainer->get_height())
            y = parentContainer->get_height() - foodSize - 10;
    }
}

bool FoodManager::generateFood(const Snake &snake, FoodType type)
{
    if (foods.size() >= maxFoodCount)
        return false;

    int x, y;
    int attempts = 0;
    const int maxAttempts = 100; // 防止无限循环

    do
    {
        getRandomPosition(x, y);
        attempts++;
    } while (attempts < maxAttempts &&
             (!isValidPosition(x, y, snake) || !isPositionSafe(x, y, snake)));

    if (attempts >= maxAttempts)
    {
        std::cout << "无法找到合适的食物生成位置" << std::endl;
        return false;
    }

    foods.push_back(std::make_unique<Food>(parentContainer, x, y, foodSize, type));
    std::cout << "生成食物于位置: (" << x << ", " << y << ")" << std::endl;
    return true;
}

bool FoodManager::generateRandomFood(const Snake &snake)
{
    int maxAttempts = 10; // 最大尝试次数，避免无限循环
    int attempts = 0;

    while (attempts < maxAttempts)
    {
        int x, y;
        getRandomPosition(x, y);

        if (isValidPosition(x, y, snake) && isPositionSafe(x, y, snake))
        {
            // 根据概率决定食物类型
            FoodType type = FOOD_NORMAL;
            int randValue = disType(gen);

            if (randValue < Probability * 1)
            { // 10% 概率生成增益食物
                type = FOOD_BUFF;
            }
            else if (randValue < Probability * 2)
            { // 10% 概率生成减益食物
                type = FOOD_DEBUFF;
            }
            else if (randValue < Probability * 3)
            { // 10% 概率生成辣椒
                type = FOOD_PEPPER;
            }
            else if (randValue < Probability * 4)
            { // 10% 概率生成冰激凌
                type = FOOD_ICE_CREAM;
            }
            else if (randValue < Probability * 5)
            { // 10% 概率生成甜甜圈
                type = Donut;
            }
            else if (randValue < Probability * 6)
            { // 10% 概率生成蛋糕
                type = Cake;
            }
            else if (randValue < Probability * 7)
            { // 10% 概率生成甜甜圈
                type = Milk;
            }
            else if (randValue < Probability * 8)
            { // 10% 概率生成蛋糕
                type = Candied_hawthorn;
            }
            try
            {
                foods.push_back(std::make_unique<Food>(
                    parentContainer, x, y, foodSize, type));
                return true;
            }
            catch (const std::exception &e)
            {
                std::cout << "生成食物失败: " << e.what() << std::endl;
                return false;
            }
        }
        attempts++;
    }

    std::cout << "无法找到有效位置生成食物" << std::endl;
    return false;
}

bool FoodManager::generateFoodIfNeeded(const Snake &snake)
{
    // 如果食物数量不足，就生成新食物
    if (foods.size() < maxFoodCount)
    {
        return generateRandomFood(snake);
    }
    return false;
}

Food *FoodManager::checkCollision(const Snake &snake)
{
    if (!snake.getHead() || foods.empty())
        return nullptr;

    int headX = snake.getHead()->get_pos_x();
    int headY = snake.getHead()->get_pos_y();
    int headSize = snake.getSegmentSize();

    for (auto it = foods.begin(); it != foods.end(); ++it)
    {
        auto &food = *it;
        if (!food || !food->getContainer())
            continue;

        int foodX = food->getX();
        int foodY = food->getY();
        int foodSize = food->getSize();

        // 更精确的碰撞检测
        bool xCollision = (headX < foodX + foodSize) && (headX + headSize > foodX);
        bool yCollision = (headY < foodY + foodSize) && (headY + headSize > foodY);

        if (xCollision && yCollision)
        {
            return food.get();
        }
    }
    return nullptr;
}

void FoodManager::handleCollision(Food *food, Snake *snake)
{

    if (food == nullptr)
        return;
    // 根据食物类型处理蛇的长度
    switch (food->getType())
    {
    case FOOD_NORMAL: // 苹果 增加1长度
        snake->grow();
        break;
    case FOOD_BUFF: // 金苹果效果 增加3长度
        snake->changemoveSpeed(150);

        for (int i = 0; i < 3; i++)
            snake->grow();

        Game_Page->set_background_image("./res/background.bmp");

        snake->setBodySegmentsImage("./res/body.bmp");
        snake->change_body();

        snake->setTailImage("./res/tail.bmp");
        snake->change_tail();

        snake->setHeadImage(snake->get_Snake_head());
        snake->change_head();

        break;
    case FOOD_DEBUFF: // 毒苹果效果 减少2长度
        snake->shrink(2);
        break;
    case FOOD_PEPPER: // 辣椒效果
        snake->changemoveSpeed(50);

        Game_Page->set_background_image("./res/background_hot.bmp");

        snake->setBodySegmentsImage("./res/body_hot.bmp");
        snake->change_body_hot();

        snake->setTailImage("./res/tail_hot.bmp");
        snake->change_tail_hot();

        snake->setHeadImage("./res/head_hot.bmp");
        snake->change_head_hot();

        std::cout << "吃到辣椒！" << std::endl;
        break;
    case FOOD_ICE_CREAM: // 冰块效果
        snake->changemoveSpeed(250);

        Game_Page->set_background_image("./res/background_cold.bmp");

        snake->setBodySegmentsImage("./res/body_cold.bmp");
        snake->change_body_cold();

        snake->setTailImage("./res/tail_cold.bmp");
        snake->change_tail_cold();

        snake->setHeadImage("./res/head_cold.bmp");
        snake->change_head_cold();

        std::cout << "吃到冰块！" << std::endl;
        break;
    case Donut: //
        snake->grow();
        std::cout << "吃到甜甜圈！" << std::endl;
        break;
    case Cake: //
        snake->grow();
        std::cout << "吃到蛋糕！" << std::endl;
        break;
    case Milk: //
        snake->grow();
        std::cout << "吃到甜甜圈！" << std::endl;
        break;
    case Candied_hawthorn: //
        snake->grow();
        std::cout << "吃到蛋糕！" << std::endl;
        break;
    }

    cout << "开始删除食物" << endl;

    // 移除被吃掉的食物
    removeFood(food);
}

void FoodManager::removeFood(Food *food)
{
    if (food == nullptr)
        return;
    // return; // 这里我写return就是在检查段溢出时是不是发生在这之前，结果段溢出发生在handleCollision函数里面

    auto it = std::find_if(foods.begin(), foods.end(),
                           [food](const std::unique_ptr<Food> &f)
                           {
                               return f.get() == food;
                           });
    if (it != foods.end())
    {
        Container *foodContainer = (*it)->getContainer();

        if (foodContainer != nullptr && foodContainer->isIniParent())
        {
            Container *parent = foodContainer->getParent();
            if (parent != nullptr)
            {
                parent->removeSon(foodContainer);
            }
        }
        foods.erase(it);
    }
}

void FoodManager::clearAllFood()
{
    // 使用安全的移除方式
    while (!foods.empty())
    {
        removeFood(foods.front().get());
    }

    std::cout << "已清空所有食物，数量: " << foods.size() << std::endl;
}

void FoodManager::updateFoods(const Snake &snake)
{
    // 只需要检查是否需要生成新食物
    generateFoodIfNeeded(snake);
}